<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
    <script src="jqury.js"></script>
    <style>
      div {
        width: 500px;
        height: 500px;
        border: 1px solid;
        display: none;
      }
      .active {
        display: block;
      }
    </style>
  </head>
  <body>
    <input type="text" />
    <div></div>

    <script>
      let input = document.querySelector("input");
      let btn = document.querySelector("button");
      let div = document.querySelector("div");
      input.onfocus = function (e) {
        div.classList.add("active");
        document.addEventListener("click", addEventListener);
      };
      function addEventListener(e) {
        if (div && !div.contains(e.target)) {
          div.classList.remove("active");
          // 移除事件监听
          removeEventListener("click", addEventListener);
        }
      }
      // 阻止事件冒泡
      input.addEventListener("click", function (e) {
        e.stopPropagation();
      });
      // 键盘弹起事件
      input.onkeyup = _.debounce(function () {
        let value = input.value;
        if (input.value) {
          $.ajax({
            type: "get",
            url: "http://49.235.98.65:3000/search/content",
            data: {
              keyword: input.value,
            },
            success: function (data) {
              data = data.slice(0, 10);
              getlist(data, value);
            },
          });
        } else {
          div.innerHTML = "";
        }
      }, 500);
      // 渲染数据
      function getlist(data, value) {
        div.innerHTML = "";
        let str = ``;
        data.forEach(function (ele) {
          str += red(`<p>${ele.name}</p>`, value);
        });
        div.innerHTML = str;
      }
      // 关键字
      function red(str, keyword) {
        return str.replace(
          new RegExp(keyword, "g"),
          ` <span style="color: red;">${keyword}</span>`
        );
      }
    </script>
  </body>
</html>
